package com.powerunion.datacollection.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.Constants;
import com.powerunion.datacollection.common.Format;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.ProcessInfoDao;
import com.powerunion.datacollection.model.ActivityInfo;
import com.powerunion.datacollection.model.CollectionTaskInstance;
import com.powerunion.datacollection.model.Urgency;
import com.powerunion.datacollection.model.jsonObject.ActivityTreeNode;
import com.powerunion.datacollection.model.jsonObject.ApproveTreeNode;
import com.powerunion.datacollection.model.jsonObject.CollectionTreeNode;
import com.powerunion.datacollection.model.jsonObject.ProcDetailsTreeNode;
import com.powerunion.datacollection.persistence.db.jdbc.operator.QueryOperator;
import com.powerunion.datacollection.persistence.db.jdbc.operator.RsDataSet;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlParameter;
import com.powerunion.datacollection.persistence.db.jdbc.operator.SqlType;
import com.powerunion.datacollection.persistence.db.jdbc.operator.UpdateOperator;
import com.powerunion.datacollection.service.CollectionTaskInstanceManager;
import com.powerunion.datacollection.service.UrgencyManager;
import com.powerunion.util.DBUtils;
import com.powerunion.util.log.LogHelper;

public class ProcessInfoDaoImpl extends JdbcBase implements ProcessInfoDao {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			ProcessInfoDaoImpl.class);

	public boolean save(ActivityInfo activityInfo, String itemId)
			throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "save");
		}
		Connection conn = null;
		StringBuffer sql = new StringBuffer();
		sql
				.append(
						"insert into dc_process_table(id,item_id,para_id,activity_type,activity_name,time_limit,fillType_Or_approveType,approveUser_Or_urgencyDate,")
				.append(
						"examineUser_Or_collectionUser,description,exa_Or_col_type,iupdata,urgency_content) values(?,?,?,?,?,?,?,?,?,?,?,?,?)");

		String activityId = "";
		try {
			conn = this.getConnection();
			UrgencyManager um = new UrgencyManager();
			activityId = this.saveActivityInfo(activityInfo, sql.toString(),
					conn, "null", itemId,um);
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存流程定义环节信息出错！");
		} finally {
			DBUtils.close(conn);
		}

		if (!StringUtils.isEmpty(activityId)) {

			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程定义环节信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("save:" + Constants.SAVE + "流程定义环节信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	private String saveActivityInfo(ActivityInfo activityInfo, String sql,
			Connection conn, String paraId, String itemId,UrgencyManager um) throws DaoException {
		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "saveActivityInfo");
		}
		String resultId = "";
		PreparedStatement ps = null;
		try {
			ps = conn.prepareStatement(sql);
			int i = 1;
			resultId = String.valueOf(this.getSeq("dc_process_table"));
			ps.setString(i++, resultId);
			ps.setString(i++, itemId);
			ps.setString(i++, paraId);
			ps.setInt(i++, activityInfo.getActivityType());
			ps.setString(i++, activityInfo.getActivityName());
			ps.setString(i++, activityInfo.getTimeLimit());
			ps.setInt(i++, activityInfo.getFillTypeOrapproveType());
			String approveUserORurgencyDate = activityInfo
					.getApproveUserOrurgencyDate();
			ps.setString(i++, approveUserORurgencyDate);
			ps.setString(i++, activityInfo.getExamineUserOrcollectionUser());
			ps.setString(i++, activityInfo.getDescription());
			ps.setString(i++, activityInfo
					.getExamineUserOrcollectionUserTypes());
			ps.setInt(i++, activityInfo.getIupdata());
			ps.setString(i++, activityInfo.getUrgencyContent());

			ps.executeUpdate();
			int activityType = activityInfo.getActivityType();
			if(activityType != 0){
				
				Urgency urgency = new Urgency();
				urgency.setProcId(itemId);
				urgency.setActId(resultId);
				urgency.setRemindInfo(activityInfo.getRemindContent());
				urgency.setUrgencyContent(activityInfo.getUrgencyContent());
				urgency.setUrgeTime(activityInfo.getUrgencyDate());
				urgency.setRepeatCount(activityInfo.getRepeatCount());
				urgency.setRepeatIntervalDay(activityInfo.getRepeatIntervalDay());
				urgency.setRepeatIntervalHour(activityInfo.getRepeatIntervalHour());
				
				um.save(urgency, conn);
			}

			if (activityInfo.getData() != null
					&& activityInfo.getData().size() > 0) {
				for (Iterator iter2 = activityInfo.getData().iterator(); iter2
						.hasNext();) {
					ActivityInfo ai = (ActivityInfo) iter2.next();
					String aiId = "";
					// 递归保存
					aiId = this.saveActivityInfo(ai, sql, conn, resultId,
							itemId,um);
					if (StringUtils.isEmpty(aiId))
						break;
				}
			}

		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("保存流程环节信息出错！");
		} finally {
			DBUtils.close(ps);
		}
		return resultId;
	}

	public List getProcessInfo(String processId) throws Exception {
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		sqlString
				.append(
						"select d.id,d.item_id,d.para_id,d.activity_type,d.activity_name,d.time_limit,d.approveUser_Or_urgencyDate,d.fillType_Or_approveType,")
				.append(
						"d.examineUser_Or_collectionUser,d.description,d.exa_Or_col_type,d.iupdata,d.urgency_content,u.urge_time,u.urge_info,u.remind_info,  ")
				.append(" u.repeat_count,u.repeat_interval_day,u.repeat_interval_hour ")
				.append(" from dc_process_table d left join dc_urgency u on d.id=u.act_id and d.item_id=u.proc_id  where d.item_id=? and d.para_id=? ");

		List activityList = null;
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			activityList = this.getTreeNodes(conn, processId, "null", sqlString
					.toString());
		} catch (Exception e) {
			logger.error("", e);
			throw new Exception(Constants.SEARCH + "getProcessInfo tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private List getTreeNodes(Connection conn, String processId, String paraId,
			String sql) throws Exception {

		PreparedStatement ps = null;
		ResultSet rs = null;
		List treeNodeArray = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();
			treeNodeArray = new ArrayList();

			while (rs.next()) {
				int activityType = rs.getInt("activity_type");
				String id = rs.getString("id");
				String text = rs.getString("activity_name");
				String description = rs.getString("description");
				String examineUserORcollectionUser = rs
						.getString("examineUser_Or_collectionUser");
				String approveUserORurgencyDate = rs
						.getString("approveUser_Or_urgencyDate");
				int fillTypeOrapproveType = rs
						.getInt("fillType_Or_approveType");
				String timeLimit = rs.getString("time_limit");
				String examineUserOrcollectionUserTypes = rs
						.getString("exa_Or_col_type");
				int iupdata = rs.getInt("iupdata");
				String urgencyContent = rs.getString("urgency_content");
				String urgeTime = rs.getString("urge_time");
				String urgeInfo = rs.getString("urge_info");
				String remindInfo = rs.getString("remind_info");
				int repeatCount = rs.getInt("repeat_count");
				int repeatIntervalDay = rs.getInt("repeat_interval_day");
				int repeatIntervalHour = rs.getInt("repeat_interval_hour");
				
				switch (activityType) {
				case 0:
					ActivityTreeNode treeNode = new ActivityTreeNode();
					treeNode.setId(id);
					treeNode.setText(text);
					treeNode.setDescription(description);
					treeNode.setIconCls("processStart");
					treeNode.setType("0");
					List children = new ArrayList();
					// 递归调用
					children = this.getTreeNodes(conn, processId, treeNode
							.getId(), sql);
					if (!children.isEmpty()) {
						treeNode.setChildren(children);
						treeNode.setLeaf(false);
					}
					treeNodeArray.add(treeNode);
					break;
				case 1:
					ApproveTreeNode at = new ApproveTreeNode();
					at.setId(id);
					at.setText(text);
					at.setDescription(description);
					at.setIconCls("approveNode");
					at.setType("1");
					at.setApproveDate(timeLimit);
					at.setApproveType("审批步骤");
					at.setApproveUserCodes(approveUserORurgencyDate);
					String approveUserNames = this
							.getApproveActivityUserNames(approveUserORurgencyDate);
					at.setApproveUserNames(approveUserNames);
					at.setAuditingType(fillTypeOrapproveType);
					at.setExamineUserCodes(examineUserORcollectionUser);
					String examineUserNames = this
					.getCollectionActivityUserNames(
							examineUserORcollectionUser,
							examineUserOrcollectionUserTypes);
					at.setExamineUserNames(examineUserNames);
					at.setExamineUserTypes(examineUserOrcollectionUserTypes);
					at.setExpandable(false);
					at.setIupdata(iupdata);
					at.setUrgencyDate(urgeTime);
					at.setUrgencyContent(urgeInfo);
					at.setRemindContent(remindInfo);
					at.setRepeatCount(repeatCount);
					at.setRepeatIntervalDay(repeatIntervalDay);
					at.setRepeatIntervalHour(repeatIntervalHour);
					
					
					List atChildren = new ArrayList();
					// 递归调用
					atChildren = this.getTreeNodes(conn, processId, at.getId(),
							sql);
					if (!atChildren.isEmpty()) {
						at.setChildren(atChildren);
						at.setLeaf(false);
					}
					treeNodeArray.add(at);
					break;
				case 2:
					CollectionTreeNode ct = new CollectionTreeNode();
					ct.setId(id);
					ct.setText(text);
					ct.setDescription(description);
					ct.setIconCls("collectionUserGroup");
					ct.setType("2");
					ct.setCollectionUserCodes(examineUserORcollectionUser);
					String collectionUserNames = this
							.getCollectionActivityUserNames(
									examineUserORcollectionUser,
									examineUserOrcollectionUserTypes);
					ct.setCollectionUserNames(collectionUserNames);
					ct.setDisposalDate(timeLimit);
					ct.setExpandable(false);
					ct.setFillType(fillTypeOrapproveType);
					ct.setUrgencyDate(urgeTime);
					ct.setCollectionUserTypes(examineUserOrcollectionUserTypes);
					ct.setCollectionType("采集节点");
					ct.setUrgencyContent(urgencyContent);
					ct.setRemindContent(remindInfo);
					ct.setRepeatCount(repeatCount);
					ct.setRepeatIntervalDay(repeatIntervalDay);
					ct.setRepeatIntervalHour(repeatIntervalHour);
					ct.setLeaf(true);
					treeNodeArray.add(ct);
					break;
				}

			}

			logger.debug(Constants.SEARCH + "processinfo tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "processinfo tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
		return treeNodeArray;
	}

	public List getProcessInfoDetails(String workflowId,String procId) throws Exception {
		List activityList = null;
		//获取该流程Id的最新流程实例信息
		activityList = this.getProcessInfoDetailsByInstance(workflowId);
		if(activityList != null){
			return activityList;
		}
		
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();

		sqlString
		.append(
				"select d.id,d.item_id,d.para_id,d.activity_type,d.activity_name,d.time_limit,d.approveUser_Or_urgencyDate,d.fillType_Or_approveType,")
		.append(
				"d.examineUser_Or_collectionUser,d.description,d.exa_Or_col_type,d.iupdata,d.urgency_content,u.urge_time,u.urge_info,u.remind_info, ")
		.append(" u.repeat_count,u.repeat_interval_day,u.repeat_interval_hour, ")
		.append(" decode(sign((SELECT COUNT(d2.id) FROM dc_process_table d2 WHERE d2.para_id = d.id)), 1 , 1 , 0) childNum ")
		.append(" from dc_process_table d left join dc_urgency u on d.id=u.act_id where d.item_id=? and d.para_id=? ");
		
		
		try {
			conn = this.getConnection();
			activityList = new ArrayList();
			this.getDetailsTreeNodes(conn, procId, "null", sqlString
					.toString(), activityList);
			if (activityList.size() > 0) {
				// 反转顺序
				Collections.reverse(activityList);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new Exception(Constants.SEARCH + "getProcessInfoDetails tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private void getDetailsTreeNodes(Connection conn, String processId,
			String paraId, String sql, List activityList) throws Exception {
		logger.info(Constants.INTOMETHOD + "getDetailsTreeNodes");
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, processId);
			ps.setString(2, paraId);
			rs = ps.executeQuery();

			while (rs.next()) {
				int activityType = rs.getInt("activity_type");
				String id = rs.getString("id");
				String text = rs.getString("activity_name");
				String description = rs.getString("description");
				String examineUserORcollectionUser = rs
						.getString("examineUser_Or_collectionUser");
				String approveUserORurgencyDate = rs
						.getString("approveUser_Or_urgencyDate");
				int fillTypeOrapproveType = rs
						.getInt("fillType_Or_approveType");
				String timeLimit = rs.getString("time_limit");
				String examineUserOrcollectionUserTypes = rs
						.getString("exa_Or_col_type");
				int iupdata = rs.getInt("iupdata");
				String urgeTime = rs.getString("urge_time");
				String urgeInfo = rs.getString("urge_info");
				String remindInfo = rs.getString("remind_info");
				int repeatCount = rs.getInt("repeat_count");
				int repeatIntervalDay = rs.getInt("repeat_interval_day");
				int repeatIntervalHour = rs.getInt("repeat_interval_hour");
				
				ProcDetailsTreeNode at = new ProcDetailsTreeNode();
				at.setId(id);
				at.setDescription(description);
				at.set_parent(paraId);
				at.setActivityId(id);
				at.setActivityName(text);
				at.setActivityType(activityType);
				String approveUserNames = this
						.getApproveActivityUserNames(approveUserORurgencyDate);
				at.setApproveUserName(approveUserNames);
				at.setApproveUserOrurgencyDate(approveUserORurgencyDate);
				at.setDescription(description);
				at.setExamineUserOrcollectionUser(examineUserORcollectionUser);
				String examineUserORcollectionUserNames = this
						.getCollectionActivityUserNames(
								examineUserORcollectionUser,
								examineUserOrcollectionUserTypes);
				at.setExamineUserOrcollectionUserName(examineUserORcollectionUserNames);
				at.setExamineUserOrcollectionUserTypes(examineUserOrcollectionUserTypes);
				at.setFillTypeOrapproveType(fillTypeOrapproveType);
				at.setTimeLimit(timeLimit);
				at.setIupdata(iupdata);
				at.setUrgencyContent(urgeInfo);
				at.setUrgencyDate(urgeTime);
				at.setRemindContent(remindInfo);
				at.setRepeatCount(repeatCount);
				at.setRepeatIntervalDay(repeatIntervalDay);
				at.setRepeatIntervalHour(repeatIntervalHour);
				
//				int childrens = this.IsHasChildren(id, conn);
//				if (childrens > 0) {
//					at.setLeaf(false);
//				} else {
//					at.setLeaf(true);
//				}
				
				int childNum = rs.getInt("childNum");
				if (childNum > 0) { // 父节点
					at.setLeaf(false);
				} else {// 子节点
					at.setLeaf(true);
				}

				// 递归调用添加
				this.getDetailsTreeNodes(conn, processId, at.getId(), sql,
						activityList);
				// if(activityType != 0){
				activityList.add(at);
				// }

			}

			logger.debug(Constants.SEARCH + "getDetailsTreeNodes tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "getDetailsTreeNodes tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
	}
	
	private List getProcessInfoDetailsByInstance(String workflowId) throws Exception {
		String workInstanceId = this.getLastWorkInstnceId(workflowId);
		CollectionTaskInstance task = null;
		if(!StringUtils.isEmpty(workInstanceId)){
			CollectionTaskInstanceManager ctm = new CollectionTaskInstanceManager();
			task = ctm.findByKey(workInstanceId);
		}

		if(task == null || StringUtils.isEmpty(task.getId())){
			return null;
		}
		Connection conn = null;
		StringBuffer sqlString = new StringBuffer();
		sqlString
				.append(
						"select d.id,d.item_id,d.para_id,d.act_type,d.act_name,d.time_limit,d.appRole_Or_urgDate,d.fillType_Or_appType,")
				.append(
						"d.examRol_Or_colRol,d.description,d.exa_Or_col_type,d.iupdata,d.urgency_content,u.urge_time,u.urge_info,u.remind_info, ")
				.append(" u.repeat_count,u.repeat_interval_day,u.repeat_interval_hour, ")
				.append(" decode(sign((SELECT COUNT(d2.id) FROM dc_proc_instance d2 WHERE d2.para_id = d.id)), 1 , 1 , 0) childNum ")
				.append(" from dc_proc_instance d left join dc_urgency u on d.id=u.act_id where d.item_id=? and d.para_id=? ");
		
		List activityList = null;
		try {
			conn = this.getConnection(); 
			activityList = new ArrayList();
			this.getIntanceDetailsTreeNodes(conn, task.getProcId(), "null", sqlString
					.toString(), activityList,task.getCreateDate());
			if (activityList.size() > 0) {
				// 反转顺序
				Collections.reverse(activityList);
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new Exception(Constants.SEARCH + "getProcessInfoDetails tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(conn);
		}
		return activityList;
	}

	private void getIntanceDetailsTreeNodes(Connection conn, String procInstanceId,
			String paraId, String sql, List activityList,Date workInstanceCreateDate) throws Exception {
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, procInstanceId);
			ps.setString(2, paraId);

			rs = ps.executeQuery();

			while (rs.next()) {
				int activityType = rs.getInt("act_type");
				String id = rs.getString("id");
				String text = rs.getString("act_name");
				String description = rs.getString("description");
				String examineUserORcollectionUser = rs
						.getString("examRol_Or_colRol");
				String approveUserORurgencyDate = rs
						.getString("appRole_Or_urgDate");
				int fillTypeOrapproveType = rs
						.getInt("fillType_Or_appType");
				
				String timeLimitStr = rs.getString("time_limit");
				String timeLimit = "";
				if(!StringUtils.isEmpty(timeLimitStr)){
					Date timeLimitDate = Format.getInstance().stringToDate(timeLimitStr);
					timeLimit =  String.valueOf(Format.getInstance().daysBetween(workInstanceCreateDate, timeLimitDate));
				}

	
				String examineUserOrcollectionUserTypes = rs
						.getString("exa_Or_col_type");
				int iupdata = rs.getInt("iupdata");
				
				String urgeTimeStr = rs.getString("urge_time");
				String urgeTime = "";
				if(!StringUtils.isEmpty(urgeTimeStr)){
					Date urgeTimeDate = Format.getInstance().stringToDate(urgeTimeStr);
					urgeTime =  String.valueOf(Format.getInstance().daysBetween(workInstanceCreateDate, urgeTimeDate));
				}

				
				String urgeInfo = rs.getString("urge_info");
				String remindInfo = rs.getString("remind_info");
				int repeatCount = rs.getInt("repeat_count");
				int repeatIntervalDay = rs.getInt("repeat_interval_day");
				int repeatIntervalHour = rs.getInt("repeat_interval_hour");
				
				ProcDetailsTreeNode at = new ProcDetailsTreeNode();
				at.setId(id);
				at.setDescription(description);
				at.set_parent(paraId);
				at.setActivityId(id);
				at.setActivityName(text);
				at.setActivityType(activityType);
				String approveUserNames = this
						.getApproveActivityUserNames(approveUserORurgencyDate);
				at.setApproveUserName(approveUserNames);
				at.setApproveUserOrurgencyDate(approveUserORurgencyDate);
				at.setDescription(description);
				at.setExamineUserOrcollectionUser(examineUserORcollectionUser);
				String examineUserORcollectionUserNames = this
						.getCollectionActivityUserNames(
								examineUserORcollectionUser,
								examineUserOrcollectionUserTypes);
				at.setExamineUserOrcollectionUserName(examineUserORcollectionUserNames);
				at.setExamineUserOrcollectionUserTypes(examineUserOrcollectionUserTypes);
				at.setFillTypeOrapproveType(fillTypeOrapproveType);
				at.setTimeLimit(timeLimit);
				at.setIupdata(iupdata);
				at.setUrgencyContent(urgeInfo);
				at.setUrgencyDate(urgeTime);
				at.setRemindContent(remindInfo);
				at.setRepeatCount(repeatCount);
				at.setRepeatIntervalDay(repeatIntervalDay);
				at.setRepeatIntervalHour(repeatIntervalHour);
				
//				int childrens = this.IsHasChildren(id, conn);
//				if (childrens > 0) {
//					at.setLeaf(false);
//				} else {
//					at.setLeaf(true);
//				}
				
				int childNum = rs.getInt("childNum");
				if (childNum > 0) { // 父节点
					at.setLeaf(false);
				} else {// 子节点
					at.setLeaf(true);
				}

				// 递归调用添加
				this.getIntanceDetailsTreeNodes(conn, procInstanceId, at.getId(), sql,
						activityList,workInstanceCreateDate);
				// if(activityType != 0){
				activityList.add(at);
				// }

			}

			logger.debug(Constants.SEARCH + "getDetailsTreeNodes tree"
					+ Constants.SUCCESS);

		} catch (Exception e) {
			logger.error("getTree() of throws : ", e);
			throw new Exception(Constants.SEARCH + "getDetailsTreeNodes tree"
					+ Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}
	}

	private String getLastWorkInstnceId(String workId)throws DaoException {
		StringBuffer sql = new StringBuffer();
		sql.append("select max(id)id from dc_wf_instance where wf_id=?");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, workId));

		String id = "";

		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int j = 0; j < rs.rowCount; j++) {}

				if(rs.rowCount>0){
					id = rs.getFieldValueAsString("id");
				}
				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getLastProcInstanceId throw error!");
		}
		return id;
	}
	
	private String getCollectionActivityUserNames(String userCodes,
			String userTypes) throws DaoException {

		// 参数为空
		if (StringUtils.isEmpty(userCodes)) {
			// String[] args = { "userCodes" };
			// // 打印错误日志
			// StringBuffer msglog = new StringBuffer(
			// "empty invoke parameter userCodes NULL ");
			// logger.error(msglog.toString());
			// throw new SystemException("error.common.parameter.empty", args);
			return "";
		}

		StringBuffer userNames = new StringBuffer();

		String[] users = StringUtils.split(userCodes, ",");
		String[] types = StringUtils.split(userTypes, ",");
		Connection conn = null;
		try {
			conn = this.getConnection();
			String sql = "select f.user_name from frameuser f where f.user_code = ?";
			if(types.length != users.length){
				return "";
			}
			for (int i = 0; i < users.length; i++) {
				String code = users[i];
				String type = types[i];
				
				if (type.equals("user")) {
					sql = "select f.user_name name from frameuser f where f.user_code = ?";
				} else if (type.equals("group")) {
					sql = "select w.grop_name name from workgroup w where w.grop_code = ?";
				} else if (type.equals("department")) {
					sql = "select d.dept_name name from framedepartment d  where d.dept_code = ?";
				}

				QueryOperator query = new QueryOperator();
				query.setSql(sql);
				query.setPresentConnection(conn);
				query.setUseOnlyConnectionFlag(true);
				query.addParameter(new SqlParameter(SqlType.VARCHAR, code));
				query.access();

				if (query.resultSetAvailable()) {// 检查结果集是否可用
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());

					if (rs.rowCount > 0) {
						String userName = rs.getFieldValueAsString("name");
						if (userNames.toString().trim().equals("")) {
							userNames.append(userName);
						} else {
							userNames.append(",").append(userName);
						}

					}
					rs.clearAll();

				}

			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getUsersByActivity throw error!");
		} finally {
			DBUtils.close(conn);
		}

		return userNames.toString();
	}

	private String getApproveActivityUserNames(String userCodes)
			throws DaoException {

		// 参数为空
		if (StringUtils.isEmpty(userCodes)) {
			// String[] args = { "userCodes" };
			// // 打印错误日志
			// StringBuffer msglog = new StringBuffer(
			// "empty invoke parameter userCodes NULL ");
			// logger.error(msglog.toString());
			// throw new SystemException("error.common.parameter.empty", args);
			return "";
		}

		StringBuffer userNames = new StringBuffer();

		String[] users = StringUtils.split(userCodes, ",");
		Connection conn = null;
		try {
			conn = this.getConnection();
			String sql = "select f.user_name from frameuser f where f.user_code = ?";
			for (int i = 0; i < users.length; i++) {
				String userCode = users[i];
				QueryOperator query = new QueryOperator();
				query.setSql(sql);
				query.setPresentConnection(conn);
				query.setUseOnlyConnectionFlag(true);
				query.addParameter(new SqlParameter(SqlType.VARCHAR, userCode));
				query.access();

				if (query.resultSetAvailable()) {// 检查结果集是否可用
					// 获取并处理记录集
					RsDataSet rs = new RsDataSet(query.getSqlResultSet());

					if (rs.rowCount > 0) {
						String userName = rs.getFieldValueAsString("user_name");
						if (userNames.toString().trim().equals("")) {
							userNames.append(userName);
						} else {
							userNames.append(",").append(userName);
						}

					}
					rs.clearAll();
				}

			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("getApproveActivityUserNames throw error!");
		} finally {
			DBUtils.close(conn);
		}

		return userNames.toString();
	}

	private int IsHasChildren(String parentId, Connection conn)
			throws Exception {

		String sql = "";
		int total = 0;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			sql = "select count(*) from dc_process_table where para_id=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, parentId);

			rs = ps.executeQuery();

			if (rs.next()) {
				total = rs.getInt(1);
			}

		} catch (Exception e) {
			logger.error("IsHasChildren:" + Constants.SEARCH
					+ "proceess info children" + Constants.FAIL);
			logger.error("IsHasChildren() of throws : ", e);
			throw new Exception("IsHasChildren:" + Constants.SEARCH
					+ "proceess info children" + Constants.FAIL);
		} finally {
			DBUtils.close(rs, ps);
		}

		return total;
	}

	public boolean delete(String procId) throws DaoException {

		if (logger.isDebugEnabled()) {
			logger.debug(Constants.INTOMETHOD + "delete");
		}
		String sql = "delete from dc_process_table where item_id = ? ";
		UpdateOperator update = new UpdateOperator();
		update.setSql(sql);

		update.addParameter(new SqlParameter(SqlType.VARCHAR, procId));

		try {
			update.access();
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("删除流程ID为：" + procId + " 的所有环节信息出错！");
		}

		int effectCount = update.getEffectCounts();
		if (effectCount > 0) {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "流程信息"
						+ Constants.SUCCESS);
			}
			return true;
		} else {
			if (logger.isDebugEnabled()) {
				logger.debug("delete:" + Constants.DELETE + "流程信息"
						+ Constants.FAIL);
			}
			return false;
		}
	}

	/**
	 * 检测流程的环节信息设置
	 * 
	 * @param procId
	 * @return
	 * @throws DaoException
	 */
	public String validateActivityInfo(String procId) throws DaoException {
		logger.debug(Constants.INTOMETHOD + "validateActivityInfo");
		StringBuffer sql = new StringBuffer();
		sql
				.append("select activity_type,activity_name,")
				.append(
						"time_limit,approveUser_Or_urgencyDate,examineUser_Or_collectionUser ")
				.append("from dc_process_table where item_id = ?");
		QueryOperator query = new QueryOperator();
		query.setSql(sql.toString());
		query.addParameter(new SqlParameter(SqlType.VARCHAR, procId));

		StringBuffer validateInfo = new StringBuffer();

		try {
			query.access();
			if (query.resultSetAvailable()) {
				// 获取并处理记录集
				RsDataSet rs = new RsDataSet(query.getSqlResultSet());
				for (int j = 0; j < rs.rowCount; j++) {

					String timeLimit = rs.getFieldValueAsString("time_limit");
					String appRoleOrurgDate = rs
							.getFieldValueAsString("approveUser_Or_urgencyDate");
					String examRolOrcolRol = rs
							.getFieldValueAsString("examineUser_Or_collectionUser");
					String actName = rs.getFieldValueAsString("activity_name");
					int actType = rs.getFieldValueAsInteger("activity_type")
							.intValue();
					
					
					if(actType == 1){
						if (StringUtils.isEmpty(appRoleOrurgDate)) {
							validateInfo.append("<font color=red>").append(
									actName).append("步骤</font>:");
								validateInfo
										.append("<font color=green>【审批人】</font>没有设置||");
								validateInfo.append(" <br> ");
						}
						
					}else if(actType == 2){
						if (StringUtils.isEmpty(examRolOrcolRol)) {
							validateInfo.append("<font color=red>").append(
									actName).append("步骤</font>:");
							validateInfo
							.append("<font color=green>【采集人】</font>没有设置||");
							validateInfo.append(" <br> ");
						}
					}
					rs.next();
				}

				rs.clearAll();
			}
		} catch (Exception e) {
			logger.error("", e);
			throw new DaoException("检测流程Id为：" + procId + " 的环节步骤信息出错！");
		}
		return validateInfo.toString();
	}
	
}
